import React, { useState, useEffect } from 'react';
import { Form, Input, Button, Card, Select, message, Spin } from 'antd';
import { UserOutlined, LockOutlined, MailOutlined, IdcardOutlined } from '@ant-design/icons';
import { Link, useNavigate } from 'react-router-dom';
import { useAuth } from '../../contexts/AuthContext';

const { Option } = Select;

const Register = () => {
  const [loading, setLoading] = useState(false);
  const { register, user } = useAuth();
  const navigate = useNavigate();
  const [form] = Form.useForm();
  const [selectedRole, setSelectedRole] = useState('');

  useEffect(() => {
    // 如果用户已经登录，重定向到仪表板
    if (user) {
      navigate('/dashboard');
    }
  }, [user, navigate]);

  const onFinish = async (values) => {
    setLoading(true);
    try {
      const registerData = {
        username: values.username,
        email: values.email,
        password: values.password,
        role: values.role,
        relatedId: values.relatedId || null
      };

      const result = await register(registerData);
      if (result.success) {
        message.success('注册成功，请登录');
        navigate('/login');
      }
    } catch (error) {
      console.error('注册错误:', error);
    } finally {
      setLoading(false);
    }
  };

  const onFinishFailed = (errorInfo) => {
    console.log('表单验证失败:', errorInfo);
    message.error('请检查输入信息');
  };

  const handleRoleChange = (value) => {
    setSelectedRole(value);
    // 清除relatedId字段的值
    form.setFieldsValue({ relatedId: undefined });
  };

  const getRelatedIdLabel = () => {
    switch (selectedRole) {
      case 'STUDENT':
        return '学生ID';
      case 'TEACHER':
        return '教师ID';
      default:
        return '关联ID';
    }
  };

  const getRelatedIdPlaceholder = () => {
    switch (selectedRole) {
      case 'STUDENT':
        return '请输入学生ID（可选）';
      case 'TEACHER':
        return '请输入教师ID（可选）';
      default:
        return '请输入关联ID（可选）';
    }
  };

  return (
    <div className="login-container">
      <Card className="login-form">
        <div className="login-title">
          用户注册
        </div>
        <Form
          form={form}
          name="register"
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
          size="large"
          scrollToFirstError
        >
          <Form.Item
            name="username"
            rules={[
              {
                required: true,
                message: '请输入用户名!'
              },
              {
                min: 3,
                message: '用户名至少3个字符!'
              },
              {
                max: 20,
                message: '用户名最多20个字符!'
              }
            ]}
          >
            <Input
              prefix={<UserOutlined />}
              placeholder="用户名"
            />
          </Form.Item>

          <Form.Item
            name="email"
            rules={[
              {
                required: true,
                message: '请输入邮箱!'
              },
              {
                type: 'email',
                message: '请输入有效的邮箱地址!'
              }
            ]}
          >
            <Input
              prefix={<MailOutlined />}
              placeholder="邮箱"
            />
          </Form.Item>

          <Form.Item
            name="password"
            rules={[
              {
                required: true,
                message: '请输入密码!'
              },
              {
                min: 6,
                message: '密码至少6个字符!'
              }
            ]}
          >
            <Input.Password
              prefix={<LockOutlined />}
              placeholder="密码"
            />
          </Form.Item>

          <Form.Item
            name="confirmPassword"
            dependencies={['password']}
            rules={[
              {
                required: true,
                message: '请确认密码!'
              },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || getFieldValue('password') === value) {
                    return Promise.resolve();
                  }
                  return Promise.reject(new Error('两次输入的密码不一致!'));
                }
              })
            ]}
          >
            <Input.Password
              prefix={<LockOutlined />}
              placeholder="确认密码"
            />
          </Form.Item>

          <Form.Item
            name="role"
            rules={[
              {
                required: true,
                message: '请选择角色!'
              }
            ]}
          >
            <Select
              placeholder="选择角色"
              onChange={handleRoleChange}
            >
              <Option value="STUDENT">学生</Option>
              <Option value="TEACHER">教师</Option>
              <Option value="ADMIN">管理员</Option>
            </Select>
          </Form.Item>

          {selectedRole && selectedRole !== 'ADMIN' && (
            <Form.Item
              name="relatedId"
              rules={[
                {
                  pattern: /^\d+$/,
                  message: '请输入有效的数字ID!'
                }
              ]}
            >
              <Input
                prefix={<IdcardOutlined />}
                placeholder={getRelatedIdPlaceholder()}
                addonBefore={getRelatedIdLabel()}
              />
            </Form.Item>
          )}

          <Form.Item>
            <Button
              type="primary"
              htmlType="submit"
              loading={loading}
              block
              style={{ marginBottom: '16px' }}
            >
              {loading ? <Spin size="small" /> : '注册'}
            </Button>
            <div style={{ textAlign: 'center' }}>
              已有账号？ <Link to="/login">立即登录</Link>
            </div>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
};

export default Register;